
import 'dart:async';
import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

/// SharedPreferences 缓存工具类
/// 专注于数据缓存功能，提供通用的缓存操作
class SharedPUtil {
  static late SharedPreferences _prefs;

  SharedPUtil._();

  /// 初始化 SharedPreferences
  static Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  // ==================== 基础缓存操作 ====================
  
  /// 存储字符串
  static Future<bool> putString(String key, String value) {
    return _prefs.setString(key, value);
  }

  /// 获取字符串
  static String? getString(String key, {String? defValue}) {
    return _prefs.getString(key) ?? defValue;
  }

  /// 存储整数
  static Future<bool> putInt(String key, int value) {
    return _prefs.setInt(key, value);
  }

  /// 获取整数
  static int? getInt(String key, {int? defValue}) {
    return _prefs.getInt(key) ?? defValue;
  }

  /// 存储布尔值
  static Future<bool> putBool(String key, bool value) {
    return _prefs.setBool(key, value);
  }

  /// 获取布尔值
  static bool? getBool(String key, {bool? defValue}) {
    return _prefs.getBool(key) ?? defValue;
  }

  /// 存储双精度浮点数
  static Future<bool> putDouble(String key, double value) {
    return _prefs.setDouble(key, value);
  }

  /// 获取双精度浮点数
  static double? getDouble(String key, {double? defValue}) {
    return _prefs.getDouble(key) ?? defValue;
  }

  /// 存储字符串列表
  static Future<bool> putStringList(String key, List<String> value) {
    return _prefs.setStringList(key, value);
  }

  /// 获取字符串列表
  static List<String>? getStringList(String key, {List<String>? defValue}) {
    return _prefs.getStringList(key) ?? defValue;
  }

  // ==================== 对象缓存操作 ====================
  
  /// 存储对象（JSON序列化）
  static Future<bool> putObject(String key, Object value) {
    return _prefs.setString(key, json.encode(value));
  }

  /// 获取对象（JSON反序列化）
  static Map<String, dynamic>? getObject(String key) {
    String? data = _prefs.getString(key);
    return (data == null || data.isEmpty) ? null : json.decode(data);
  }

  /// 获取类型化对象
  static T? getObj<T>(String key, T Function(Map<String, dynamic> v) f, {T? defValue}) {
    Map<String, dynamic>? map = getObject(key);
    return map == null ? defValue : f(map);
  }

  /// 存储对象列表
  static Future<bool> putObjectList(String key, List<Object> list) {
    List<String> dataList = list.map((value) => json.encode(value)).toList();
    return _prefs.setStringList(key, dataList);
  }

  /// 获取对象列表
  static List<Map<String, dynamic>>? getObjectList(String key) {
    List<String>? dataList = _prefs.getStringList(key);
    return dataList?.map((value) => Map<String, dynamic>.from(json.decode(value))).toList();
  }

  /// 获取类型化对象列表
  static List<T>? getObjList<T>(String key, T Function(Map<String, dynamic> v) f, {List<T>? defValue}) {
    List<Map<String, dynamic>>? dataList = getObjectList(key);
    List<T>? list = dataList?.map((value) => f(value)).toList();
    return list ?? defValue;
  }

  // ==================== 缓存管理操作 ====================
  
  /// 移除指定键
  static Future<bool> remove(String key) {
    return _prefs.remove(key);
  }

  /// 清空所有缓存
  static Future<bool> clear() {
    return _prefs.clear();
  }

  /// 检查是否包含指定键
  static bool containsKey(String key) {
    return _prefs.containsKey(key);
  }

  /// 获取所有键
  static Set<String> getKeys() {
    return _prefs.getKeys();
  }

  /// 获取缓存大小
  static int getSize() {
    return _prefs.getKeys().length;
  }

  // ==================== 批量操作 ====================
  
  /// 批量存储
  static Future<bool> putBatch(Map<String, dynamic> data) async {
    try {
      for (var entry in data.entries) {
        if (entry.value is String) {
          await putString(entry.key, entry.value);
        } else if (entry.value is int) {
          await putInt(entry.key, entry.value);
        } else if (entry.value is bool) {
          await putBool(entry.key, entry.value);
        } else if (entry.value is double) {
          await putDouble(entry.key, entry.value);
        } else if (entry.value is List) {
          if (entry.value is List<String>) {
            await putStringList(entry.key, entry.value);
          } else {
            await putObjectList(entry.key, entry.value.cast<Object>());
          }
        } else {
          await putObject(entry.key, entry.value);
        }
      }
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 批量获取
  static Map<String, dynamic> getBatch(List<String> keys) {
    Map<String, dynamic> result = {};
    for (String key in keys) {
      if (containsKey(key)) {
        // 尝试获取不同类型的值
        String? stringValue = getString(key);
        int? intValue = getInt(key);
        bool? boolValue = getBool(key);
        double? doubleValue = getDouble(key);
        List<String>? stringListValue = getStringList(key);
        Map<String, dynamic>? objectValue = getObject(key);
        
        if (stringValue != null) {
          result[key] = stringValue;
        } else if (intValue != null) {
          result[key] = intValue;
        } else if (boolValue != null) {
          result[key] = boolValue;
        } else if (doubleValue != null) {
          result[key] = doubleValue;
        } else if (stringListValue != null) {
          result[key] = stringListValue;
        } else if (objectValue != null) {
          result[key] = objectValue;
        }
      }
    }
    return result;
  }

  /// 批量移除
  static Future<bool> removeBatch(List<String> keys) async {
    try {
      for (String key in keys) {
        await remove(key);
      }
      return true;
    } catch (e) {
      return false;
    }
  }
}
